package com.wy.redbag;


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

import androidx.annotation.Nullable;

/**
 * Time:2021/9/23
 * Author:ypf
 * Description:
 */
public class RedBagView extends View {


    private String TAG = "RedBagView";

    private static final long PROGRESS_EXECUTE_TIME = 600;

    private static final long SHRINK_EXECUTE_TIME = 3 * 1000;

    private Paint mProgressPaint;

    private Bitmap mRedPackageBitmap;
    private Bitmap mProgressBgBitmap;

    private float mTotalProgress = 100;
    private float mCurrentProgress = 0;

    private float mBombProgress = 0;
    private float mTotalBombRadius = 0;

    private int mProgressStarColor = Color.RED;
    private int mProgressEndColor = Color.YELLOW;

    //爆炸的个数
    private int mBombNumber = 8;
    // #XFÊJicon
    private Bitmap[] mBombIcon = new Bitmap[8];

    public RedBagView(Context context) {
        this(context, null, 0);
    }

    public RedBagView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RedBagView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {

        mProgressPaint = new Paint();
        mProgressPaint.setColor(Color.RED);

        mRedPackageBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.hongbao);
        mProgressBgBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ddd);

        mTotalBombRadius = mProgressBgBitmap.getHeight();
        Bitmap bomb1 = BitmapFactory.decodeResource(getResources(), R.drawable.pop1);
        Bitmap bomb2 = BitmapFactory.decodeResource(getResources(), R.drawable.pop2);

        mBombIcon[0] = bomb1;
        mBombIcon[1] = bomb2;

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 指定大小为宽高最大的值 * 1.1 ，为什么要多 0.1 是由于有爆炸效果
        int size = (int) (Math.max(mRedPackageBitmap.getWidth(), mRedPackageBitmap.getHeight()) * 1.1f);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(size, size);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 先绘制静态内容
        int viewHeight = getHeight();
        int viewWidth = getWidth();

        // 绘制红包
        canvas.drawBitmap(mRedPackageBitmap, 0, 0, null);
        // 绘制进度条背景,必须匹配上红包位置，只能按比例计算,而且还有适配所有机型
        int progressBgWidth = mProgressBgBitmap.getWidth();
        int left = (int) (progressBgWidth * 0.09f);
        int top = viewHeight - mProgressBgBitmap.getHeight() - left;
        canvas.drawBitmap(mProgressBgBitmap, left, top, null);

        // 绘制进度
        if (mTotalProgress == 0 || mCurrentProgress == 0) {
            return;
        }

        int bombCenterX = 0;
        int bombCenterY = 0;

        // 这些只能慢慢调试，不能出现任何跟 px dp 有关的单位，只能按比例调试
        int progressHeight = (int) (mProgressBgBitmap.getHeight() * 0.25f);
        float progressWidth = viewWidth * 0.64f;
        int currentProgressWidth = (int) (progressWidth * mCurrentProgress / mTotalProgress);
        int round = progressHeight / 2;
        // 设置进度条渐变颜色
        Shader shader = new LinearGradient(0, 0, progressWidth, 0, new int[]{mProgressStarColor, mProgressEndColor}, new float[]{0, 1.0f}, Shader.TileMode.CLAMP);
        mProgressPaint.setShader(shader);
        top = (int) (top * 1.19f);
        left = (int) (left * 2.5f);
        RectF rectF = new RectF(left, top, left + currentProgressWidth, top + progressHeight);
        canvas.drawRoundRect(rectF, round, round, mProgressPaint);

        bombCenterX = left + currentProgressWidth;
        bombCenterY = top;

        //爆炸的动画，准备几个Bitmap for循环，计算半径
        //绘制六个小圆坐标
        float preAngle = (float) (2 * Math.PI / mBombNumber);
        for (int i = 0; i < mBombNumber; i++) {
            //初始角度+当前旋转的角度
            double angle = i * preAngle;
            float mCurrentBombRadius = mTotalBombRadius * mBombProgress;
            float cx = (float) (bombCenterX + mCurrentBombRadius * Math.cos(angle));
            float cy = (float) (bombCenterY + mCurrentBombRadius * Math.sin(angle));
            canvas.drawBitmap(mBombIcon[i % 2], cx, cy, null);
        }

    }

    public void startAnimator(int from, int to) {
        // 属性动画
        ValueAnimator animator = ValueAnimator.ofFloat(from, to).setDuration(PROGRESS_EXECUTE_TIME);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 不断的设置当前进度刷新进度效果
                float current = (float) animation.getAnimatedValue();
                setCurrentProgress(current);
            }
        });
        animator.start();

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                executeDisperseBombAnimator();
            }
        });

    }

    // 绘制爆炸的动画
    private void executeDisperseBombAnimator() {

        ValueAnimator animator = ValueAnimator.ofFloat(0, 1f).setDuration(600);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mBombProgress = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
        animator.setInterpolator(new DecelerateInterpolator());
        animator.start();

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                // 绘制完爆炸以后如果是满格，执行缩小动画
                if (mCurrentProgress == mTotalProgress) {

                }
            }
        });
    }

//    private AnimatorSet mShrinkAnimators;
//
//    /**
//     * 执行缩小动画
//     */
//    private void executeShrinkAnimator() {
//        if (mShrinkAnimators == null) {
//            mShrinkAnimators = new AnimatorSet();//组合动画
//            ObjectAnimator scaleX = ObjectAnimator.ofFloat(this, "scaleX", 1f, SHRINK_SCALE);
//            ObjectAnimator scaleY = ObjectAnimator.ofFloat(this, "scaleY", 1f, SHRINK_SCALE);
//
//            mShrinkAnimators.setDuration(SHRINK_EXECUTE_TIME);
//            mShrinkAnimators.setInterpolator(new DecelerateInterpolator());
//            mShrinkAnimators.play(scaleX).with(scaleY);//两个动画同时开始
//            mShrinkAnimators.start();
//
//            mShrinkAnimators.addListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    // mHandler.sendEmptyMessageDelayed(0x0011, 200);
//                    executeMagnifyAnimator();
//                }
//            });
//        }
//
//        mShrinkAnimators.start();
//
//        mHandler.sendEmptyMessageDelayed(0x0022, SHRINK_EXECUTE_TIME - 100);
//    }
//
//    private AnimatorSet mMagnifyAnimators;
//
//    /**
//     * 执行放大的效果
//     */
//    private void executeMagnifyAnimator() {
//
//        if (mMagnifyAnimators == null) {
//            mMagnifyAnimators = new AnimatorSet();//组合动画
//            ObjectAnimator scaleX = ObjectAnimator.ofFloat(this, "scaleX", SHRINK_SCALE, 1f);
//            ObjectAnimator scaleY = ObjectAnimator.ofFloat(this, "scaleY", SHRINK_SCALE, 1f);
//
//            mMagnifyAnimators.setDuration(MAGNIFY_EXECUTE_TIME);
//            mMagnifyAnimators.setInterpolator(new DecelerateInterpolator());
//            mMagnifyAnimators.play(scaleX).with(scaleY);//两个动画同时开始
//
//
//            mMagnifyAnimators.addListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    mHandler.sendEmptyMessageDelayed(0x0011, ANIMATION_STOP_TIME);
//                }
//            });
//        }
//        mMagnifyAnimators.start();
//    }

    private synchronized void setCurrentProgress(float currentProgress) {
        this.mCurrentProgress = currentProgress;
        invalidate();
    }

    public void setTotalProgress(float totalProgress) {
        this.mTotalProgress = totalProgress;
    }

}